package cn.chanel.mall.service.impl;

import cn.chanel.mall.admin.vo.AdminUserVO;
import cn.chanel.mall.entity.User;
import cn.chanel.mall.repository.UserRepository;
import cn.chanel.mall.service.UserService;
import cn.chanel.mall.utils.DataFormatUtil;
import cn.chanel.mall.utils.KeyUtil;
import lombok.val;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;

    @Override
    public User loginOrRegister(String email, String password) {
        val user = userRepository.findUserByEmail(email);
        if(user != null){
            // 登录
            if(user.getEmail().equals(email) && user.getPassword().equals(password)){
                return user;
            }else {
                // 登录失败
                return null;
            }
        }else {
            // 注册
            final User newUser = new User();
            newUser.setId(KeyUtil.genUniqueKey());
            newUser.setEmail(email);
            newUser.setPassword(password);
            // 暂定邮箱为用户昵称
            newUser.setName(email);
            newUser.setCreateTime(System.currentTimeMillis());
            return userRepository.save(newUser);
        }
    }

    @Override
    public User findUserById(String userId) {
        return userRepository.findById(userId).orElse(null);
    }

    @Override
    public List<AdminUserVO> getAllUser() {
        val userList = userRepository.findAll();
        final ArrayList<AdminUserVO> adminUserVOS = new ArrayList<>(userList.size());
        userList.forEach(e -> {
            adminUserVOS.add(convert(e));
        });
        return adminUserVOS;
    }

    @Override
    public List<AdminUserVO> getAllUserByKey(String key) {
        val userList = userRepository.findAllByIdContainsOrEmailContains(key, key);
        final ArrayList<AdminUserVO> adminUserVOS = new ArrayList<>(userList.size());
        userList.forEach(e -> {
            adminUserVOS.add(convert(e));
        });
        return adminUserVOS;
    }

    private AdminUserVO convert(User e) {
        final AdminUserVO adminUserVO = new AdminUserVO();
        adminUserVO.setId(e.getId());
        adminUserVO.setName(e.getName());
        adminUserVO.setEmail(e.getEmail());
        adminUserVO.setCreateTime(DataFormatUtil.formatDate(e.getCreateTime()));
        return adminUserVO;
    }
}
